package com.hnevc.androiduiclassone8;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);

        String jsonString = "{\"name\":\"tom\",\"password\":\"123\",\"address\":{\"country\":\"中国\",\"city\":\"长沙\"}}";
        String jsonArraystring = "[12,54,52,23,14]";

        try {
            JSONArray array = new JSONArray(jsonArraystring);
            for (int i = 0 ; i < array.length(); i++){
                int num = array.getInt(i);
                Toast.makeText(this, ""+num, Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        try {
            JSONObject object = new JSONObject(jsonString);
           String name= object.getString("name");
           JSONObject address = object.getJSONObject("address");
           String country = address.getString("country");
            Toast.makeText(this, country, Toast.LENGTH_SHORT).show();
            Toast.makeText(this, name, Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
